package com.open.rbac.config.security.handler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.open.center.common.model.CommonResult;
import com.open.center.common.util.JSON;

/**
 * 没有访问权限的处理
 *
 * @author Riche's
 * @since 2022/8/15
 */
@Service
public class MeAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().write(JSON.toJson(CommonResult
                .fail(StringUtils.hasText(accessDeniedException.getMessage())
                        ? accessDeniedException.getMessage() : "没有访问权限")));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
